package com.async.config;

import cn.hutool.core.util.ArrayUtil;
import com.async.annotation.AsyncExec;
import com.async.dto.ProxyMethodDto;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Method;

/**
 * <p>
 * 异步收集方法
 * </p>
 * @author yang
 * @date 2024/5/16
 */
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
@ConditionalOnProperty(prefix = "async", value = "enabled", havingValue = "true")
public class AsyncInitBean implements BeanPostProcessor {

    @Autowired
    private AsyncProxyContext asyncProxyContext;

    /**
     * 初始化之前执行，将所有带有AsyncExec注解的方法替换成代理对象
     * @param bean bean原型
     * @param beanName bean名称
     */
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        // 反射获取类的所有方法
        Method[] methods = ReflectionUtils.getAllDeclaredMethods(bean.getClass());
        if (ArrayUtil.isEmpty(methods)){
            return bean;
        }
        // 将方法进行缓存
        for (Method method : methods) {
            AsyncExec asyncExec = AnnotationUtils.findAnnotation(method, AsyncExec.class);
            if (asyncExec == null){
                continue;
            }
            ProxyMethodDto proxyMethodDto = new ProxyMethodDto();
            proxyMethodDto.setBean(bean);
            proxyMethodDto.setMethod(method);

            // 方法唯一标识
            String key = asyncProxyContext.getAsyncMethodKey(bean,method);
            asyncProxyContext.setAsyncMethod(key,proxyMethodDto);
        }
        return bean;
    }
}
